package cn.lzd.mr.me;

import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * Created by lzd on 2018/7/21.
 */
public class CommonCount {

    public static class MyMapper extends Mapper<Object, Text, Text, IntWritable> {

        Text out = new Text();
        IntWritable outVal = new IntWritable(1);

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String str = value.toString();
            try {
                JSONObject json = JSONObject.parseObject(str);
                String createTime = json.getString("createTime");
                LocalDateTime localDateTime = LocalDateTime.parse(createTime);
                out.set(localDateTime.getHour() + "");
                context.write(out, outVal);
            } catch (Exception e) {

            }
        }
    }

    public static class MyReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        IntWritable outVal = new IntWritable();

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for (IntWritable value : values) {
                count += value.get();
            }
            outVal.set(count);
            context.write(key, outVal);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);
        job.setJarByClass(CommonCount.class);

        job.setMapperClass(CommonCount.MyMapper.class);
        job.setReducerClass(CommonCount.MyReduce.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path("E:\\testmg\\test2"));
        FileOutputFormat.setOutputPath(job, new Path("E:/testmg/out/"));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
